import { debounceTime } from 'rxjs/operators';
import { Component, OnInit, OnDestroy } from '@angular/core';
import { compareDataField } from 'src/app/common/tools/condition-tool';
import { Condition } from 'src/app/models/condition';
import { PermitConfig } from '../../../models';
import { BaseFieldComponent } from '../base-field/base-field.component';

@Component({
  selector: 'zepride-project-number',
  templateUrl: './project-number.component.html',
  styleUrls: ['./project-number.component.less', '../field.common.less']
})
export class ProjectNumberComponent extends BaseFieldComponent implements OnInit, OnDestroy {
  codeObj;
  codeRuleList: {
    codeName?: string;
    condition?: Condition
  }[] = [];

  initValue;

  permitConfig: PermitConfig[] = [
    { mode: 'query', permitId: '查看', permitName: '', authObjectId: '' },
    { mode: 'edit', permitId: '编辑', permitName: '', authObjectId: '' }
  ];

  async ngOnInit() {
    this.codeRuleList = this.componentData.extends.codeRuleList;
    this.initValue = this.bindData;
    await this.getOrgCode();

    this.registerModelChange();
  }

  async getOrgCode() {
    if (this.codeRuleList && !this.initValue) {
      for (const item of this.codeRuleList) {
        if (item.condition) {
          const result = compareDataField(this.dataModel, item.condition);
          if (!result) {
            break;
          }
        }

        this.codeObj = await this.orgSvr.getNewOrgCode(item.codeName);
        this.setData(this.codeObj.code);
      }
    }
  }

  registerModelChange() {
    this.modelChange$ = this.engineService.dataModelChange$.pipe(
      debounceTime(200)
    ).subscribe(async data => {
      if (data.identifyId !== this.componentData.identifyId) {
        // 判断条件是否发生变更
        if (this.codeRuleList && !this.initValue) {
          for (const item of this.codeRuleList) {
            if (item.condition) {
              const result = compareDataField(this.dataModel, item.condition);
              if (result) {
                this.codeObj = await this.orgSvr.getNewOrgCode(item.codeName);
                this.setData(this.codeObj.code);
                break;
              }
            }
          }
        }
      }
    });
  }

  pageSavedHandle = async () => {
    if (this.codeObj) {
      await this.orgSvr.saveOrgCode(this.codeObj.seedId);
    }
  }

  ngOnDestroy() {
    if (this.modelChange$) {
      this.modelChange$.unsubscribe();
    }
  }

}
